<?php
/**
 * 得到最上级用户id
 * @param $id 需要查询的用户id
 * @return mixed
 * @author 杨希成
 */
function mogo_get_pid($id)
{
    $user = $this->get_find(['id' => $id]);
    if ($user->group_id == 2) return $user->id;
    $user_all = collection($this->get_select())->toArray();
    $pids = get_parent_id($user_all, $user->pid);
    foreach ($pids as $v) {
        if ($v['group_id'] == 2) {
            return $v['id'];
        }
    }
}
/**
 * 查询所有下级
 * @param $array      需要筛选的数组
 * @param $parent_id  要查询的id
 * @return array
 * @author 杨希成
 */
function mogo_get_children_id($array, $parent_id)
{
    $arr = array();
    foreach ($array as $v) {
        if ($v['pid'] == $parent_id) {
            $arr[] = $v;
            $arr = array_merge($arr, get_children_id($array, $v['id']));
        }
    }
    return $arr;
}
/**
 * 得到随机小数使用案例
 * @param $mix_num
 * @param $max_num
 * @return float|int
 * @author 杨希成
 */

function mogo_get_rand($mix_num,$max_num){
    $FloatLength = getFloatLength($mix_num);
    $jishu_rand = pow(10, $FloatLength);
    $shop_min = $mix_num * $jishu_rand;
    $shop_max = $max_num * $jishu_rand;
    $rand = rand($shop_min, $shop_max) / $jishu_rand;
    return $rand;
}
/**
 * //计算小数点后位数
 * @param $num
 * @return int
 * @author 杨希成
 */
function mogo_getFloatLength($num) {
    $count = 0;
    $temp = explode ( '.', $num );
    if (sizeof ( $temp ) > 1) {
        $decimal = end ( $temp );
        $count = strlen ( $decimal );
    }
    return $count;
}
/**
 * @param $num 科学计数法字符串  如 2.1E-5
 * @param int $double 小数点保留位数 默认5位
 * @return string
 * @author 杨希成
 */
function mogo_sctonum($num, $double = 5)
{
    if (false !== stripos($num, "e")) {
        $a = explode("e", strtolower($num));
        return bcmul($a[0], bcpow(10, $a[1], $double), $double);
    }
    return $num;
}
/**
 * 数字格式化
 * @author 杨希成
 */
function mogo_num_format($num){
    if(!is_numeric($num)){
        return false;
    }
    $num = explode('.',$num);//把整数和小数分开
    $rl = $num[1];//小数部分的值
    $j = strlen($num[0]) % 3;//整数有多少位
    $sl = substr($num[0], 0, $j);//前面不满三位的数取出来
    $sr = substr($num[0], $j);//后面的满三位的数取出来
    $i = 0;
    $rvalue = '';
    while($i <= strlen($sr)){
        $rvalue = @$rvalue.','.substr($sr, $i, 3);//三位三位取出再合并，按逗号隔开
        $i = $i + 3;
    }
    $rvalue = $sl.$rvalue;
    $rvalue = substr($rvalue,0,strlen($rvalue)-1);//去掉最后一个逗号
    $rvalue = explode(',',$rvalue);//分解成数组
    if($rvalue[0]==0){
        array_shift($rvalue);//如果第一个元素为0，删除第一个元素
    }
    $rv = $rvalue[0];//前面不满三位的数
    for($i = 1; $i < count($rvalue); $i++){
        $rv = $rv.','.$rvalue[$i];
    }
    if(!empty($rl)){
        $rvalue = $rv.'.'.$rl;//小数不为空，整数和小数合并
    }else{
        $rvalue = $rv;//小数为空，只有整数
    }
    return $rvalue;
}
/**
 * 限制字符长度，用...代替
 * @param $sourcestr string
 * @param $cutlength string
 * @return string
 * @author 杨希成
 */
function mogo_cut_str($sourcestr,$cutlength)
{
    $returnstr='';
    $i=0;
    $n=0;
    $str_length=strlen($sourcestr);//字符串的字节数
    while (($n<$cutlength) and ($i<=$str_length))
    {
        $temp_str=substr($sourcestr,$i,1);
        $ascnum=Ord($temp_str);//得到字符串中第$i位字符的ascii码
        if ($ascnum>=224)    //如果ASCII位高与224，
        {
            $returnstr=$returnstr.substr($sourcestr,$i,3); //根据UTF-8编码规范，将3个连续的字符计为单个字符
            $i=$i+3;            //实际Byte计为3
            $n++;            //字串长度计1
        }
        elseif ($ascnum>=192) //如果ASCII位高与192，
        {
            $returnstr=$returnstr.substr($sourcestr,$i,2); //根据UTF-8编码规范，将2个连续的字符计为单个字符
            $i=$i+2;            //实际Byte计为2
            $n++;            //字串长度计1
        }
        elseif ($ascnum>=65 && $ascnum<=90) //如果是大写字母，
        {
            $returnstr=$returnstr.substr($sourcestr,$i,1);
            $i=$i+1;            //实际的Byte数仍计1个
            $n++;            //但考虑整体美观，大写字母计成一个高位字符
        }
        else                //其他情况下，包括小写字母和半角标点符号，
        {
            $returnstr=$returnstr.substr($sourcestr,$i,1);
            $i=$i+1;            //实际的Byte数计1个
            $n=$n+0.5;        //小写字母和半角标点等与半个高位字符宽...
        }
    }
    if ($str_length>$i){
        $returnstr = $returnstr . "...";//超过长度时在尾处加上省略号
    }
    return $returnstr;
}
/**
 * 得到发布时间差
 * @param $time
 * @return string
 * @author 杨希成
 */
function mogo_get_time($time){
    $now=date('Y-m-d H:i:s');
    $date=floor((strtotime($now)-strtotime($time))/86400);                  //天
    $hour=floor((strtotime($now)-strtotime($time))%86400/3600);             //时
    $minute=floor((strtotime($now)-strtotime($time))%86400/60);             //分
    $second=floor((strtotime($now)-strtotime($time))%86400%60);             //秒
    if($date){
        return $date.'天前';
    }else if($hour){
        return $hour.'小时前';
    }else if($minute){
        return $minute.'分钟前';
    }else{
        return '刚刚';
    }
}

/**
 *发送http请求
 * @param string $url
 */
if(!function_exists('get_curl')){
    function get_curl($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
}

/**
 * 修改图片所有编辑器内容中图片路径
 * @param string $content
 */
function get_path_img($content){
    /*    $pattern="/<img.*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/";*/
    $pattern="/\/public(.*?(?:[\.gif|\.jpg]))[\\' | \"]/";
    $path='http://'.$_SERVER['SERVER_NAME'];
    if (empty($content)) return $content;
    preg_match_all($pattern, $content, $match);
//    dump($match[0]);die;
    if (empty($match[0])) {
        return $content;
    }
    $path='https://'.$_SERVER['SERVER_NAME'];
    $str=preg_replace_callback($pattern,
        function($matchs) use ($path) {
            return $path.$matchs[0];
        },$content);
    return $str;
}

/**
 * 字符串截取，支持中文和其他编码
 * static
 * access public
 * @param string $str 需要转换的字符串
 * @param string $length 截取长度
 * @param string $start 开始位置
 * @param string $charset 编码格式
 * @param string $suffix 截断显示字符
 * return string
 */
function msubstr($str,$length, $start=0, $charset="utf-8", $suffix=true) {
    if(function_exists("mb_substr")){
        $slice = mb_substr($str, $start, $length, $charset);
        $strlen = mb_strlen($str,$charset);
    }elseif(function_exists('iconv_substr')){
        $slice = iconv_substr($str,$start,$length,$charset);
        $strlen = iconv_strlen($str,$charset);
    }else{
        $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("",array_slice($match[0], $start, $length));
        $strlen = count($match[0]);
    }
    if($suffix && $strlen>$length)$slice.='...';
    return $slice;
}

/**
 * 统一错误码
 * @param string $msg
 * @param array $extra
 * @return \think\response\Json
 */
function mogo_error($msg='no message',$extra =[],$is_show=''){
    return json(['error'=>$msg,'extra'=>$extra,'is_show'=>$is_show],400);
}

/**
 * 统一返回数据
 * @param array $data
 * @param string $extra
 * @return \think\response\Json
 */
function mogo_json($data=[],$extra=''){
    return json(['data'=>$data,'extra'=>$extra]);
}

//获取内容中的图片并设置大小
function set_image_size($content, $size = '80%', $wid = 800){
    if (empty($content)) {
        return false;
    }

    if (!is_numeric($wid)) {
        $wid = 800;
    }

    if (ismobile()) {
        $wid = 288;
    }

    $data['size'] = $size;
    $data['wid'] = $wid;

    //$content = htmlspecialchars_decode($content);//如果内容为htmlspecialchars转换字符类型
    // <img src="/Uploads/Editor/2017-03-21/58d0cf4bc3565.jpg" width="670" height="335" alt="" />
    // $preg = "/<img (.*) width=\"(\d*)\" height=\"(\d*)\"(.*)\/>/iU";
    $preg = "/<img(.*)src=\"(.*)\"(.*)\/>/iU";
    preg_match_all($preg, $content, $match);
    if (empty($match[2])) {
        return $content;
    }
    // $imagesize = getimagesize($_SERVER['DOCUMENT_ROOT'].$match[1][0]);
    $res = preg_replace_callback($preg,
        function($matches) use($data){
            $imagesize = getimagesize($_SERVER['DOCUMENT_ROOT'].$matches[2]);//$_SERVER['HTTP_HOST']
            // dump($matches);
            if ($imagesize[0] >= $data['wid']) {
                $params = str_replace(' ', '', $matches[1]) == '' ? $matches[3] : $matches[1];
                $param = explode(' ', $params);
                foreach ($param as $key => $value) {
                    if ($value) {
                        $str = explode('=', $value);
                        if ($str[0] == 'width' || $str[0] == 'height') {
                            unset($param[$key]);
                        }
                    }
                }
                $param = implode(' ', $param);
                // dump($matches[2]);die();
                //  $matches[2]='http://'.$_SERVER['SERVER_NAME'].$matches[2];
                return "<img src=\"" . $matches[2] . "\" width='" . $data['size'] . "' height='" . $data['size'] . "'" . $param . " />";
            }else{
                return $matches[0];
            }
        }, $content);
    return $res;
}

/* 判断是否是手机端 */
function ismobile() {
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
        return true;

    //此条摘自TPM智能切换模板引擎，适合TPM开发
    if(isset ($_SERVER['HTTP_CLIENT']) &&'PhoneClient'==$_SERVER['HTTP_CLIENT'])
        return true;
    //如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset ($_SERVER['HTTP_VIA']))
        //找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], 'wap') ? true : false;
    //判断手机发送的客户端标志,兼容性有待提高
    if (isset ($_SERVER['HTTP_USER_AGENT'])) {
        $clientkeywords = array(
            'nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile'
        );
        //从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
            return true;
        }
    }
    //协议法，因为有可能不准确，放到最后判断
    if (isset ($_SERVER['HTTP_ACCEPT'])) {
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
            return true;
        }
    }
    return false;
}

/**
 * POST请求https接口返回内容
 * @param  string $url [请求的URL地址]
 * @param  string $data [请求的参数]
 * @return  string
 */
function api_notice_increment($url, $data){
    $ch = curl_init();
    $header = "Accept-Charset: utf-8";
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
//        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $tmpInfo = curl_exec($ch);
    //     var_dump($tmpInfo);
    //    exit;
    if (curl_errno($ch)) {
        return false;
    }else{
        // var_dump($tmpInfo);
        return $tmpInfo;
    }
}


